package com.systemic.websocket;

import com.systemic.dto.LoginUserDto;
import com.systemic.pojo.User;
import com.systemic.service.UserService;
import com.systemic.utils.UidExtractorUtils;
import com.systemic.vo.LoginSucceeded;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URI;
import java.util.Map;

/**
 * @ClassName: ChatHandshakeInterceptor
 * @Description: 定义拦截器, websocket的链接建立是基于http握手协议，添加一个拦截器处理握手之前和握手之后过程
 * @Author:
 * @CreateTime: 2024-01-01 15:40
 * @Version:
 **/
@Component
public class ChatHandshakeInterceptor implements HandshakeInterceptor {


    @Resource
    private UserService userService;

    private static String uid;


    /**
     * 握手之前
     * @param request
     * @param response
     * @param webSocketHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {

        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
//            HttpSession session = servletRequest.getServletRequest().getSession(false);
            // 获取请求URI中的参数
            URI uri = servletRequest.getURI();
            String queryString = uri.getQuery(); // 获取查询字符串，包含参数
            uid = UidExtractorUtils.makeUid(queryString);
            Integer userId = Integer.valueOf(uid);
            LoginUserDto loginUser = userService.findById(userId);
            try {
                if (loginUser != null){
                    //将用户放入socket处理器的会话(WebSocketSession)中
                    attributes.put(uid, loginUser);
                    System.out.println("Websocket:用户[ID:" + (loginUser.getUid() +"]要建立连接"));
                }
            } catch (Exception e) {
                throw new RuntimeException("--------------握手已失败..."+e);
            }
        }
        System.out.println("--------------握手开始...");
        return true;
    }

    /**
     * 握手之后
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param e
     */
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("--------------握手成功啦...");
    }
}
